<template>
  <el-container>
    <vHeadSpace />
    <el-container>
      <vAsideSpace />
      <el-container>
        <el-main class="user_main">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <el-row>
                  <div class="my-inline-block top-width-1">
                    <el-button type='success' size="small" @click='handleAdd' icon='el-icon-plus'>新增用户
                    </el-button>
                  </div>
                </el-row>
              </div>
              <!--                       表格-->
              <el-table
                      ref="multipleTable"
                      :data="tableSetting.tableData"
                      tooltip-effect="dark"
                      style="width: 100%"
                      @selection-change="handleSelectionChange">
                <el-table-column
                        prop="userId"
                        label="工号"
                >
                </el-table-column>
                <el-table-column
                        prop="username"
                        label="用户名">
                </el-table-column>
                <el-table-column
                        prop="realName"
                        label="真实名称">
                </el-table-column>
                <el-table-column
                        prop="role"
                        label="用户角色">
                </el-table-column>
                <el-table-column
                        prop="userOrganization"
                        label="单位">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                            size="mini"
                            @click="taleOperateColumnEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="taleOperateColumnDelete(scope.$index, scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!--分页-->
              <div style="margin-top: 30px;">
                <el-pagination align='right'
                               background
                               @size-change="sizeChange"
                               @current-change="currentChange"
                               :current-page="pageNumber"
                               :page-sizes="[1,3,5,10,20,50]"
                               :page-size="pageSize"
                               layout="total,prev, pager, next,sizes"
                               :total="tableSetting.tableLength">
                </el-pagination>
              </div>
            </el-card>
            <!--新建角色-->
            <el-dialog width="40%" top='12vh'
                       :title="'新增用户'"
                       :visible.sync="dialogAddUserVisible"
                       @close="cancelAddUserBtn"
            >
              <div style="width: 70%;">
                <!--                            添加用户表单-->
                <el-form
                        ref="roleInfo"
                        label-width="80px"
                        :rules="addUserRules"
                        size="small"
                        :model="roleInfo">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="roleInfo.username" autofocus/>
                  </el-form-item>
                  <el-form-item label="密码" prop="password" autocomplete="off">
                    <el-input type="password" v-model="roleInfo.password"/>
                  </el-form-item>
                  <el-form-item label="确认密码" prop="checkPassword" autocomplete="off">
                    <el-input type="password" v-model="roleInfo.checkPassword"/>
                  </el-form-item>
                  <el-form-item label="真实名称" prop="realName">
                    <el-input v-model="roleInfo.realName"/>
                  </el-form-item>
                  <el-form-item label="工号" prop="userId">
                    <el-input v-model="roleInfo.userId"/>
                  </el-form-item>
                  <el-form-item label="单位" prop="organization">
                    <el-input v-model="roleInfo.organization"/>
                  </el-form-item>
                  <el-form-item label="用户角色" prop="userRole">
                    <el-select v-model="roleInfo.userRole" placeholder="请分配用户角色">
                      <el-option
                              v-for="(role,index) in roles"
                              :key="index"
                              :label="role"
                              :value="role">
                      </el-option>
                    </el-select>
                    <!--                                    <el-input v-model="roleInfo.userRole"/>-->
                  </el-form-item>
                </el-form>
              </div>
              <!--权限树-->
              <!--                        <el-tree ref='treeEdit' default-expand-all show-checkbox check-strictly accordion-->
              <!--                                 node-key='id'-->
              <!--                                 :data='treeData'-->
              <!--                                 :props='defaultProps'-->
              <!--                                 :default-expand-all='false'-->
              <!--                                 :default-checked-keys='defaultCheckedKeys'-->
              <!--                                 :default-expanded-keys='defaultExpandedKeys'-->
              <!--                                 @check-change='handleNodeClick'/>-->

              <span slot="footer" class="text-align-right">
                            <el-button @click="cancelAddUserBtn" size="small">取消</el-button>
                            <el-button type="primary" @click="addUserConfirmOperate" size="small" :loading="addUserFormLoading">确定</el-button>
                          </span>
            </el-dialog>
            <!--编辑角色-->
            <el-dialog width="40%" top='12vh'
                       :title="'编辑角色'"
                       :visible.sync="dialogEditUserVisible"
                       @close="cancelEditUserBtn"
            >
              <div style="width: 70%;">
                <!--                            编辑用户表单-->
                <el-form
                        ref="roleInfoEdit"
                        label-width="80px"
                        :rules="editUserRules"
                        size="small"
                        :model="roleInfoEdit">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="roleInfoEdit.username" autofocus/>
                  </el-form-item>
                  <el-form-item label="密码" prop="password" autocomplete="off">
                    <el-input type="password" v-model="roleInfoEdit.password"/>
                  </el-form-item>
                  <el-form-item label="确认密码" prop="checkPassword" autocomplete="off">
                    <el-input type="password" v-model="roleInfoEdit.checkPassword"/>
                  </el-form-item>
                  <el-form-item label="真实名称" prop="realName">
                    <el-input v-model="roleInfoEdit.realName"/>
                  </el-form-item>
                  <el-form-item label="工号" prop="userId">
                    <el-input v-model="roleInfoEdit.userId" disabled/>
                  </el-form-item>
                  <el-form-item label="单位" prop="organization">
                    <el-input v-model="roleInfoEdit.organization"/>
                  </el-form-item>
                  <el-form-item label="用户角色" prop="userRole">
                    <el-select v-model="roleInfoEdit.userRole" placeholder="请分配用户角色">
                      <el-option
                              v-for="(role,index) in roles"
                              :key="index"
                              :label="role"
                              :value="role">
                      </el-option>
                    </el-select>
                    <!--                                    <el-input v-model="roleInfoEdit.userRole"/>-->
                  </el-form-item>
                </el-form>
              </div>
              <!--权限树-->
              <!--                        <el-tree ref='treeEdit' default-expand-all show-checkbox check-strictly accordion-->
              <!--                                 node-key='id'-->
              <!--                                 :data='treeData'-->
              <!--                                 :props='defaultProps'-->
              <!--                                 :default-expand-all='false'-->
              <!--                                 :default-checked-keys='defaultCheckedKeys'-->
              <!--                                 :default-expanded-keys='defaultExpandedKeys'-->
              <!--                                 @check-change='handleNodeClick'/>-->

              <span slot="footer" class="text-align-right">
                            <el-button @click="cancelEditUserBtn" size="small">取消</el-button>
                            <el-button type="primary" @click="editUserConfirmOperate" size="small" :loading="editUserFormLoading">确定</el-button>
                          </span>
            </el-dialog>
        </el-main>
        <vFootSpace/>
      </el-container>
    </el-container>
  </el-container>


</template>

<script>
    export default {
            name: "User",
            data(){
                // 添加用户验证
                var validatePassword = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error('请输入密码'));
                    } else {
                        if (this.roleInfo.checkPassword !== '') {
                            this.$refs.roleInfo.validateField('checkPassword');
                        }
                        callback();
                    }
                };
                var validateCheckPassword = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error('请再次输入密码'));
                    } else if (value !== this.roleInfo.password) {
                        callback(new Error('两次输入密码不一致!'));
                    } else {
                        callback();
                    }
                };
                // 编辑用户验证
                var validatePasswordEdit = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error('请输入密码'));
                    } else {
                        if (this.roleInfoEdit.checkPassword !== '') {
                            this.$refs.roleInfoEdit.validateField('checkPassword');
                        }
                        callback();
                    }
                };
                var validateCheckPasswordEdit = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error('请再次输入密码'));
                    } else if (value !== this.roleInfoEdit.password) {
                        callback(new Error('两次输入密码不一致!'));
                    } else {
                        callback();
                    }
                };
                return {
                    tableData: [],  //表格数据
                    multipleSelection: '',  //存储多选的内容
                    pageNumber: 1, //页数
                    pageSize: 5, //每页显示的数目
                    dialogAddUserVisible: false, // dialog新增角色 visible
                    dialogEditUserVisible: false, // dialog编辑角色 visible
                    roles: [],  //存放角色列表
                    roleInfo:{    //角色信息
                        username: '', //用户名
                        password: '', //密码
                        checkPassword: '', //确认密码
                        realName: '', //真实名称
                        userId: '', //工号
                        organization: '', //单位
                        userRole: '' //用户角色
                    },
                    roleInfoEdit:{    //角色信息
                        username: '', //用户名
                        password: '', //密码
                        checkPassword: '', //确认密码
                        realName: '', //真实名称
                        userId: '', //工号
                        organization: '', //单位
                        userRole: '' //用户角色
                    },
                    tableSetting:{
                        tableData: [], //表格数据
                        tableLength: 0, //表格数据的长度
                    },
                    addUserFormLoading: false, //添加用户的load
                    editUserFormLoading: false, //编辑用户的load
                    addUserRules:{
                        username:[{
                            required: true, message: '请输入用户名', trigger: 'blur'
                        }],
                        password:[{
                            required: true,validator: validatePassword, trigger: 'blur'
                        }],
                        checkPassword:[{
                            required: true,validator: validateCheckPassword, trigger: 'blur'
                        }],
                        realName:[{
                            required: true, message: '请输入真实名称', trigger: 'blur'
                        }],
                        userId:[{
                            required: true, message: '请输入工号', trigger: 'blur'
                        }],
                        organization:[{
                            required: true, message: '请选择单位', trigger: 'blur'
                        }],
                        userRole:[{
                            required: true, message: '请选择用户角色', trigger: 'blur'
                        }],
                    },    //添加用户表单校验的规则
                    editUserRules:{
                        username:[{
                            required: true, message: '请输入用户名', trigger: 'blur'
                        }],
                        password:[{
                            required: true,validator: validatePasswordEdit, trigger: 'blur'
                        }],
                        checkPassword:[{
                            required: true,validator: validateCheckPasswordEdit, trigger: 'blur'
                        }],
                        realName:[{
                            required: true, message: '请输入真实名称', trigger: 'blur'
                        }],
                        userId:[{
                            required: true, message: '请输入工号', trigger: 'blur'
                        }],
                        organization:[{
                            required: true, message: '请选择单位', trigger: 'blur'
                        }],
                        userRole:[{
                            required: true, message: '请选择用户角色', trigger: 'blur'
                        }],
                    },    //编辑用户表单校验的规则
                    addUserCancel: '',  //添加用户cancel token
                    editUserCancel: '',  //编辑用户cancel token
                };
            },
            methods:{
                // 新增   弹出新增界面
                handleAdd(){
                    this.dialogAddUserVisible = true;
                },
                // 删除  复合删除
                handleDelete(){
                    console.log(this.multipleSelection);
                    // let userList = [];
                    // for (let i = 0; i < this.multipleSelection.length; i++) {
                    //     userList.push(this.multipleSelection[i].userId);
                    // }
                    // console.log(userList);
                    // //发送删除请求
                    // this.sendDeleteUserRequest(userList);
                },
                //查询
                handleSearch(){

                },
                // 表格全选
                handleSelectionChange(val) {
                    console.log(val);
                    this.multipleSelection = val;
                },
                //用户列表table size 改变
                sizeChange(val){
                    this.pageNumber = 1;
                    this.pageSize = val;
                    // 重新向后端请求数据
                    this.getUserTableData();
                },
                //用户列表table page第几页 改变
                currentChange(pageNumber){
                    this.pageNumber = pageNumber;
                    // 重新向后端请求数据
                    this.getUserTableData();
                },
                // 提交表单
                submitForm(formName) {
                    var validateSuccess = false;
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            console.log('submit!!');
                            validateSuccess = true;
                            return true;
                        } else {
                            console.log('error submit!!');
                            validateSuccess = false;
                            return false;
                        }
                    });
                    return validateSuccess;
                },
                // 重置表单
                resetForm(formName) {
                    this.$refs[formName].resetFields();
                },
                // 新增确定操作  向后台发送新增的请求
                addUserConfirmOperate(){
                    // 发送请求前先验证
                    var validateSuccess = this.submitForm('roleInfo');
                    if(validateSuccess){
                        //验证成功发送请求
                        this.addUserFormLoading = true;
                        this.$axios({
                            method:"post",
                            url:"/user/add_user.action",
                            data:{
                                userId:this.roleInfo.userId,
                                username:this.roleInfo.username,
                                password:this.roleInfo.password,
                                realName:this.roleInfo.realName,
                                userOrganization:this.roleInfo.organization,
                                role:this.roleInfo.userRole,
                                logSwitch: 'true'
                            },
                            cancelToken: new this.$axios.CancelToken((c)=> { // 设置 cancel token
                                this.addUserCancel = c;
                            })
                        })
                            .then((response)=> {
                                console.log(response);
                                //只要response 表示一次请求已经做完
                                this.addUserCancel = '';
                                if(response.data.status){
                                    this.addUserFormLoading = false;
                                    // 关闭dialog
                                    this.dialogAddUserVisible = false;
                                    // 显示添加成功
                                    this.addUserSuccessMsg();
                                    // 重置表单   也可不重置
                                    this.resetForm('roleInfo');
                                    // 退出来同时重新请求所有用户
                                    this.getUserTableData();
                                }else{
                                    this.addUserFormLoading = false;
                                    this.addUserErrorMsg();
                                }
                            })
                            .catch((error)=> {
                                console.log(error);
                                this.addUserFormLoading = false;
                                // 显示添加失败信息
                                this.addUserErrorMsg();
                                //添加失败 表单不重置
                            })
                    }
                },
                // 添加用户成功信息
                addUserSuccessMsg(){
                    this.$message({
                        message: '用户添加成功',
                        type: 'success'
                    });
                },
                // 添加用户失败信息
                addUserErrorMsg(){
                    this.$message({
                        message: '用户添加失败',
                        type: 'error'
                    });
                },
                // 取消添加用户信息
                cancelAddUserMsg(){
                    this.$message({
                        type: "message",
                        message: "已取消添加用户",
                    });
                },
                //删除成功信息
                deleteUserSuccessMsg(){
                    this.$message({
                        type: "success",
                        message: "删除用户成功",
                    });
                },
                //删除成功信息
                deleteUserFailMsg(){
                    this.$message({
                        type: "message",
                        message: "删除用户失败",
                    });
                },
                // 新增用户表单的取消按钮
                cancelAddUserBtn(){
                    // 拦截还未完成的添加用户请求
                    if(typeof this.addUserCancel =='function'){
                        this.addUserCancel();
                        this.cancelAddUserMsg();
                    }
                    //待完成的一点  点击添加按钮，如果数据还没有返回，此时点击取消按钮应该取消前面的拦截添加操作返回的数据  还没有做
                    this.addUserFormLoading = false;  //应该是要删除的
                    this.dialogAddUserVisible = false;
                    //取消按钮点击时还需要把表单内容重置
                    this.resetForm('roleInfo');
                },
                //  表格的编辑操作
                taleOperateColumnEdit(index, row) {
                    console.log(index, row);
                    this.getUserInfo(row.userId); //把用户信息填进添加表里面
                    // this.roleInfoEdit.username = row.username;
                    this.dialogEditUserVisible = true;
                },
                // 表格的删除操作
                taleOperateColumnDelete(index, row) {
                    console.log(index, row);
                    this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        //发送删除请求
                        this.sendDeleteUserRequest(row.userId);
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                },
                // 得到用户信息
                getUserInfo(userId){
                    this.$axios({
                        method:"post",
                        url:"/user/get_user_by_user_id.action",
                        data:{
                            userId: userId
                        }
                    })
                        .then((response)=> {
                            let user = response.data.content.user;
                            this.roleInfoEdit.username = user.username;
                            this.roleInfoEdit.password = user.password;
                            this.roleInfoEdit.checkPassword = user.password;
                            this.roleInfoEdit.realName = user.realName;
                            this.roleInfoEdit.userId = user.userId;
                            this.roleInfoEdit.organization = user.userOrganization;
                            this.roleInfoEdit.userRole = user.role;
                        })
                        .catch((error)=> {
                            console.log(error);
                        })
                },
                //发送删除用户请求
                sendDeleteUserRequest(userList){
                    var deleteAllLastPageData = false;
                    //总计对当前页显示数目取余等于待删除的数据长度（userList.length）&&pageNumber==能分的总页数（到最后一页）
                    console.log('------------');
                    console.log(this.tableSetting.tableLength);
                    console.log(this.pageSize);
                    console.log(this.tableSetting.tableLength % this.pageSize);
                    console.log(this.pageNumber);
                    console.log(this.tableSetting.tableLength/this.pageSize);
                    if(((this.tableSetting.tableLength%this.pageSize==1)&&(this.pageNumber==Math.ceil(this.tableSetting.tableLength/this.pageSize)))
                        ||((this.pageSize==1)&&(this.pageNumber==this.tableSetting.tableLength))){
                        //满足这个条件（对最后一页数据进行操作，表示最后一页的数据被删除完了） pageNumber应该减1
                        deleteAllLastPageData = true;
                    }
                    this.$axios({
                        method:"post",
                        url:"/user/delete_user.action",
                        data:{
                            userId: userList
                        }
                    })
                        .then((response)=> {
                            console.log(response);
                            if(response.data.status){
                                this.deleteUserSuccessMsg();
                                if(deleteAllLastPageData){
                                    this.pageNumber = this.pageNumber - 1;
                                }
                                //删除成功 重新请求数据
                                this.getUserTableData();
                            }else{
                                this.deleteUserFailMsg();
                            }
                        })
                        .catch((error)=> {
                            console.log(error);
                            this.deleteUserFailMsg();
                        })
                },
                editUserConfirmOperate(){
                    // 发送请求前先验证
                    var validateSuccess = this.submitForm('roleInfoEdit');
                    if(validateSuccess){
                        this.sendEditRequest();
                    }
                },
                // 发送编辑请求
                sendEditRequest(){
                    this.editUserFormLoading = true;
                    this.$axios({
                        method:"post",
                        url:"/user/change_user.action",
                        data:{
                            userId:this.roleInfoEdit.userId,
                            username:this.roleInfoEdit.username,
                            password:this.roleInfoEdit.password,
                            realName:this.roleInfoEdit.realName,
                            userOrganization:this.roleInfoEdit.organization,
                            role:this.roleInfoEdit.userRole
                        },
                        cancelToken: new this.$axios.CancelToken((c)=> { // 设置 cancel token
                            this.editUserCancel = c;
                        })
                    })
                        .then((response)=> {
                            console.log(response);
                            this.editUserFormLoading = false;
                            this.editUserCancel = '';
                            if(response.data.status){
                                this.$message({
                                    type: "success",
                                    message: "修改成功",
                                });
                                this.dialogEditUserVisible = false;
                                this.getUserTableData();
                                this.resetForm('roleInfoEdit');
                            }else{
                                this.$message({
                                    type: "error",
                                    message: "修改失败",
                                });
                            }
                        })
                        .catch((error)=> {
                            console.log(error);
                            this.editUserFormLoading = false;
                            this.$message({
                                type: "error",
                                message: "修改失败",
                            });
                        })
                },
                cancelEditUserMsg(){
                    this.$message({
                        type: "message",
                        message: "取消修改",
                    });
                },
                // 取消编辑用户信息
                cancelEditUserBtn(){
                    // 拦截还未完成的编辑用户请求
                    if(typeof this.editUserCancel =='function'){
                        this.editUserCancel();
                        this.cancelEditUserMsg();
                    }
                    this.editUserFormLoading = false;
                    this.dialogEditUserVisible = false;
                    //取消按钮点击时还需要把表单内容重置
                    this.resetForm('roleInfoEdit');
                },
                // 得到管理的用户列表表格数据
                getUserTableData(){
                    this.$axios({
                            method:"post",
                            url:"/user/get_user_by_page_number.action",
                            data:{
                                pageSize: this.pageSize,
                                pageNumber: this.pageNumber
                            }
                        }
                    )
                        .then((response)=> {
                            console.log(response);
                            var pageInfo = response.data.content.pageInfo;
                            this.tableSetting.tableData = pageInfo.list;
                            this.tableSetting.tableLength = pageInfo.total;
                        })
                        .catch((error)=> {
                            console.log(error);
                        })
                },
                // 获取所有角色
                getAllRoles(){
                    this.$axios({
                        url: '/role/get_role_by_page_number.action',
                        method: 'post',
                        data: {
                            pageNumber: '1',
                            pageSize: '1000'
                        }
                    }).then((response)=>{
                        console.log('角色返回数据：',response);
                        let tempRoleList = response.data.content.pageInfo.list;
                        let roles = [];
                        for (let i = 0; i < tempRoleList.length; i++) {
                            roles.push(tempRoleList[i].roleName);
                        }
                        this.roles = roles;
                    }).catch((error)=>{
                        console.log(error);
                    })
                }
            },
            mounted() {
                this.getUserTableData();
                this.getAllRoles();
            }
        }

</script>

<style scoped >
    .user_main{
      padding: 10px;
      height: 92vh;
      width: 100%;
      margin-top: 56px;
    }
    .box-card{
        /*min-height: 100%;*/
    }
    .search_btn{
        text-align: right;
    }
    .my-inline-block{
        display: inline-block;
    }
    /*顶部三块区域*/
    .top-width-1{
        width: 30%;
    }
    .top-width-2{
        width: 60%;
        padding-left: 40%;
    }
    .top-width-3{
        width: 10%;
    }
    .text-align-right{
        text-align: right;
    }
    /deep/ .el-select.el-select--small{
        width: 100%;
    }
</style>
